package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.*;
import cn.com.connext.scrm.service.dto.CouponCrmDTO;
import cn.com.connext.scrm.service.dto.CrmErrorDTO;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.PointDTO;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.utils.DateUtils;
import cn.com.connext.scrm.utils.EntityUtils;
import cn.com.connext.scrm.utils.ExcelUtil;
import cn.com.connext.scrm.utils.RedisUtils;
import cn.com.connext.scrm.utils.wdtutils.WebUtils;
import cn.com.connext.scrm.web.rest.enums.LogisticsPushStateEnum;
import cn.com.connext.scrm.web.rest.enums.OrderTypeEnum;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.*;
import cn.com.connext.scrm.web.rest.resp.CouponQueryResp;
import cn.com.connext.scrm.web.rest.resp.OrderCreateResp;
import cn.com.connext.scrm.web.rest.resp.OrderExcelResp;
import cn.com.connext.scrm.web.rest.resp.OrderResp;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.Predicate;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

// import org.apache.commons.collections4.CollectionUtils;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    private final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private AccessTokenImpl accessTokenImpl;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CrmCouponRepository crmCouponRepository;

    @Autowired
    private CouponRepository couponRepository;

    @Autowired
    private TaskServiceImpl taskService;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private TaskRecordRepository taskRecordRepository;

    @Autowired
    private PrizeGoodRepository prizeGoodRepository;

    @Autowired
    private PrizeRepository prizeRepository;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    @Autowired
    private TaskRepository taskRepository;

    @Override
    public JsonResult save(OrderReq req)  {
        JsonResult jsonResult = new JsonResult();
        String key = req.getProductId();
        Boolean resultRedis = redisUtils.setIfAbsent(key, key);
        log.info("resultRedis={}", resultRedis);
        List<OrderRecord> orderRecordResult = new ArrayList<OrderRecord>();
        try {
            if (resultRedis) {
                //判断会员等级
                // Product product = productRepository.findOne(req.getProductId());
                OrderRecord order ;
                List<Product> productListByName = productRepository.getProductListByName(req.getOrderName());
                for (Product product : productListByName) {
                    //库存校验--
                    if (product.getStock().compareTo(req.getCount()) < 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("库存不足，无法兑换");
                        return jsonResult;
//                      continue;
                    }
                    //1有赞卷每个人只可以兑换一次
                    if (product.getType().compareTo(1) == 0) {
                        List<OrderRecord> orderRecords = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                        if (CollectionUtils.isNotEmpty(orderRecords)) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("该产品每人只可兑换一次，无法重复兑换");
                            return jsonResult;
                        }
                    }
                    // 2优惠卷
                    if (product.getType().compareTo(2) == 0) {
                        //查询优惠卷库存
                        CrmCoupon crmCoupon = crmCouponRepository.findOne(product.getCouponId());
                        if (null == crmCoupon) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("优惠券异常，请联系管理员");
                            return jsonResult;
                        }
                        //库存校验
                        if (crmCoupon.getStore().compareTo(req.getCount()) < 0) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("优惠券库存不足，无法兑换");
                            return jsonResult;
                        }
                        //查询改优惠卷顾客兑换次数
                        List<OrderRecord> orderRecordList = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                        String count = String.valueOf(orderRecordList.size());
                        if (crmCoupon.getDrawLimit().compareTo(count) <= 0) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("该优惠券已达兑换上限，无法兑换");
                            return jsonResult;
                        }
                    }
                    //乐观锁更新库存---
                    Integer stock = product.getStock() - req.getCount();

                    Integer update = productRepository.updateStock(stock, product.getStock(), product.getId());
                    if (update < 1) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("系统异常，请重新兑换");
                        return jsonResult;
                    }
                    //扣取积分
                    String accessToken = accessTokenImpl.getAccessToken();
                    String requestUrl = Constants.PointDecr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                    log.info("requestUrl={}", requestUrl);
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    Date currentTime = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(currentTime);
                    calendar.add(Calendar.HOUR, -8);
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    String timeStamp = formatter.format(calendar.getTime());
                    //调用微信请求实体
                    Integer countPoints = product.getPoints() * req.getCount();
                    PointDTO pointDTO = new PointDTO();
                    pointDTO.setPoint(countPoints);
                    pointDTO.setContentName(product.getName());
                    pointDTO.setDate(timeStamp);
                    pointDTO.setPattern(1);//互动积分传值"3"，积分兑换传值"1"
                    //remark 存放头像  和订单号
                    String getOrderCode = getOrderCode();//订单号
                    String getHeadImage = StringUtils.isNotBlank(product.getHeadImage()) ? product.getHeadImage() : null;
                    Map<String, Object> map = new HashMap<>();
                    map.put("orderCode", getOrderCode);
                    map.put("headImage", getHeadImage);
                    pointDTO.setRemark(JSON.toJSONString(map));
                    pointDTO.setSource("帝亚吉欧会员俱乐部");
                    HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(pointDTO), headers);
                    JSONObject result = restTemplate.postForObject(requestUrl, httpEntity, JSONObject.class);
                    log.info("积分兑换返回信息: {}", result.toString());
                    Object error = result.getJSONObject("error");
                    if (null != error) {
                        log.info("调用crm接口返回error!");
                        CrmErrorDTO crmErrorDTO = JSON.parseObject(JSON.toJSONString(error), CrmErrorDTO.class);
                        log.info("积分兑换异常返回信息: {}", crmErrorDTO.toString());
                        //添加库存   remove分布式锁
                        productRepository.updateStock(product.getStock(), stock, product.getId());
                        redisUtils.remove(key);
                        if (crmErrorDTO.getCode().compareTo("409180") == 0) {
                            jsonResult.setState(1);
                            jsonResult.setData(crmErrorDTO);
                            jsonResult.setMessage("积分不足，无法兑换");
                            return jsonResult;
                        }
                        jsonResult.setState(1);
                        jsonResult.setData(crmErrorDTO);
                        jsonResult.setMessage("积分兑换异常，请重新尝试");
                        return jsonResult;
                    }
                    PointDTO pointDto = JSON.parseObject(JSON.toJSONString(result), PointDTO.class);
                    //优惠卷需要分配couponId
                    order  = new OrderRecord();
                    if (0==product.getType()) {
                        // 实物
                        order.setState(0);
                        order.setOrderType(OrderTypeEnum.ORDER_TYPE_20.getCode());
                    } else {
                        order.setState(1);
                        // 有赞券 微信券
                        order.setOrderType(OrderTypeEnum.ORDER_TYPE_10.getCode());
                        order.setCouponId(product.getCouponId());
                    }  //  Cannot find local variable 'productRespList'
                    BeanUtils.copyProperties(req, order);
                    order.setOrderCode(getOrderCode);
                    order.setType(product.getType());
                    order.setOrderTime(new Date());
                    order.setCreateTime(new Date());
                    order.setUpdateTime(new Date());
                    //添加下发物流状态
                    order.setLogisticsPushState(LogisticsPushStateEnum.LOGISTICS_PUSH_10.getCode());
                    //设置订单总积分
                    order.setPoints(product.getPoints());
                    //物流地址
                    order.setLogisticsAddress(req.getLogisticsAddress());
                    if(StringUtils.isNotEmpty(req.getSkuId())){
                        order.setSkuId(req.getSkuId());
                    }

                    orderRecordResult.add(order);
                    //order = orderRepository.saveAndFlush(order);
                    OrderResp orderResp = new OrderResp();
                    BeanUtils.copyProperties(order, orderResp);
                    OrderCreateResp orderCreateResp = new OrderCreateResp();
                    orderCreateResp.setOrderResp(orderResp);
                    orderCreateResp.setPointDTO(pointDto);
                    List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(req.getUserId(),12);
                    if(list == null || list.size() == 0){
                        // 增加：2021-12-20 原因：增加unionid的真伪判断
                        //根据membershipId 查询member表 获取会员用户
                        Member member = memberRepository.getMembershipId(req.getMembershipId());
                        if (null == member){
                            log.info("没有获取到会员信息 req: {}",JSON.toJSONString(req));
                            jsonResult.setState(1);
                            jsonResult.setMessage("没有获取到会员信息");
                            return jsonResult;
                        }
                         Task task =taskRepository.findOne("12");
                        // 用会员用户的union_id + task.getType() 这两个字段查询
                        List<TaskRecord> taskRecordList = taskRecordRepository.findByUserIdAndTaskType(member.getUnionId(), task.getType());
                        //验证返回数据大于等于1
                        if (taskRecordList.size() >= 1) {
                            log.info("非法操作 req: {}",JSON.toJSONString(req));
                            jsonResult.setState(1);
                            jsonResult.setMessage(task.getType().compareTo(12) == 0 ? "参与积分兑换超过一次无法获取积分" : "参与积分兑换超过一次无法获取积分");
                            return jsonResult;
                        }
                        // end-------2021-12-20
                        TaskRecord taskRecord = new TaskRecord();
                        taskRecord.setCreateTime(new Date());
                        taskRecord.setTaskType(12);
                        taskRecord.setUserId(req.getUserId());
                        taskRecordRepository.save(taskRecord);
                        log.info("本地第一次积分兑礼添加积分完成");
                        String requestUrl1 = Constants.PointIncr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                        PointDTO dto = new PointDTO();
                        dto.setContentName("第一次兑换赠送积分");
                        dto.setSource("帝亚吉欧会员俱乐部");
                        dto.setDate(timeStamp);
                        dto.setPattern(1);//第一次积分兑礼
                        dto.setPoint(20);
                        OkHttpClient client = new OkHttpClient().newBuilder()
                            .build();
                        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
                        Request request = new Request.Builder()
                            .url(requestUrl1)
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                        try {
                            Response response = client.newCall(request).execute();
                            String jsresult = new String(response.body().bytes());
                            log.info("调用加分接口,返回值:{}", jsresult);
                            response.body().close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    jsonResult.setState(0);
                    jsonResult.setData(orderCreateResp);
                    redisUtils.remove(key);
                };
            } else {
                jsonResult.setState(1);
                jsonResult.setMessage("系统异常，请重试");
            }
        } catch (RestClientException e) {
            redisUtils.remove(key);
            jsonResult.setState(1);
            jsonResult.setMessage("系统异常，请重试");
        } finally {
            //生成订单(商品名字一样，只生成一个订单)----可能会有问题(防止上边返回结果里拿不到的数据)***
            if (CollectionUtils.isNotEmpty(orderRecordResult)){
                OrderRecord orderRecord = orderRepository.saveAndFlush(orderRecordResult.get(0));
                OrderResp orderResp = new OrderResp();
                BeanUtils.copyProperties(orderRecord, orderResp);
                OrderCreateResp orderCreateResp = new OrderCreateResp();
                orderCreateResp.setOrderResp(orderResp);
                jsonResult.setData(orderCreateResp);
            }
            redisUtils.remove(key);
        }
        return jsonResult;
    }

    @Override
    public JsonResult page(OrderQueryReq req) {
        PageImpl<OrderResp> pageTasks = cover(req);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(pageTasks);
        jsonResult.setState(0);
        return jsonResult;
    }

    @Override
    public JsonResult detail(String req) {
        OrderRecord order = orderRepository.findByOrderCode(req);
        OrderResp orderResp = new OrderResp();
        if (null != order) {
            BeanUtils.copyProperties(order, orderResp);
        }
        if (null != order && StringUtils.isNotBlank(order.getProductId())) {
            //如果good type 不为空 则查询prizegood 信息
            if (StringUtils.isNotBlank(order.getGoodType())) {
                PrizeGood byId = prizeGoodRepository.findOne(Integer.valueOf(order.getProductId()));
                orderResp.setType(byId.getType());
                orderResp.setPoints(0);
                orderResp.setPointCount(0);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(orderResp.getOrderTime());
                calendar.add(Calendar.HOUR, 8);
                orderResp.setOrderTime(calendar.getTime());
                orderResp.setAppletDateTime(calendar.getTime().getTime());
            } else {
                Product product = productRepository.findOne(order.getProductId());
                orderResp.setPointCount(orderResp.getCount() * product.getPoints());
                orderResp.setType(product.getType());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(orderResp.getOrderTime());
                calendar.add(Calendar.HOUR, 8);
                orderResp.setOrderTime(calendar.getTime());
                orderResp.setAppletDateTime(calendar.getTime().getTime());
                if (product.getType().compareTo(1) == 0) {
                    orderResp.setCouponId(order.getCouponId());
                    orderResp.setCouponUrl(product.getUrl());
                }
            }
        }else{
            String couponId = orderResp.getCouponId();
            if (couponId.compareTo("9333557") == 0 || couponId.compareTo("9557455") == 0) {
                List<Coupon> coupons = couponRepository.findByCouponId(couponId);
                if (CollectionUtils.isNotEmpty(coupons)) {
                    Coupon coupon = coupons.get(0);
                    orderResp.setOrderName(coupon.getCouponName());
                    orderResp.setHeadImgUrl("https://wxadmin.singlemalts.com.cn/group1/M00/01/94/rBOeiF77BRKAc3i9AAAI-Qs5Cjk356_640x10000.jpg");
                }
            }
            orderResp.setCount(1);
        }
        Member member = memberRepository.findByUnionId(order.getUserId());
        orderResp.setMemberMobile(member.getMobile());
        orderResp.setNickName(member.getNickName());
        orderResp.setHeadImgUrl(member.getHeadImgUrl());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(0);
        jsonResult.setData(orderResp);
        return jsonResult;
    }

    @Override
    public JsonResult update(OrderUpdateReq req) {
        OrderRecord order = orderRepository.findByOrderCode(req.getId());
        if (StringUtils.isNotBlank(req.getOrderON())) {
            order.setOrderON(req.getOrderON());
            order.setState(1);
            order = orderRepository.saveAndFlush(order);
        }
        OrderResp orderResp = new OrderResp();
        BeanUtils.copyProperties(order, orderResp);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(orderResp);
        jsonResult.setState(1);
        return jsonResult;
    }

    @Override
    public JsonResult callBack(OrderCallBackReq req) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(req.getCouponId()) || StringUtils.isBlank(req.getUnionId())) {
            jsonResult.setMessage(MyErrorCode.ERROR_INPUT.getMessage());
            jsonResult.setState(1);
            return jsonResult;
        }
        //根据有赞卷id 查询产品
        Product product = productRepository.findByCouponId(req.getCouponId());
        if (null == product) {
            jsonResult.setMessage("该有赞券商品不存在");
            jsonResult.setState(1);
            return jsonResult;
        }
        List<OrderRecord> orderRecordList = orderRepository.findByUserIdAndProductId(req.getUnionId(), product.getId());
        if (CollectionUtils.isEmpty(orderRecordList)) {
            jsonResult.setMessage("领取记录不存在，请联系管理员");
            jsonResult.setState(1);
            return jsonResult;
        }
        OrderRecord orderRecord = orderRecordList.get(0);
        orderRecord.setState(1);
        orderRepository.saveAndFlush(orderRecord);
        jsonResult.setMessage("更新成功");
        jsonResult.setState(0);
        return jsonResult;
    }

    @Override
    public Workbook exportOrderItemExcel(OrderQueryExcelReq req) {
        Sort sort = new Sort(Sort.Direction.DESC, "orderTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Specification<OrderRecord> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //顾客姓名
            if (StringUtils.isNotBlank(req.getName())) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + req.getName() + "%"));
            }
            //产品名字
            if (StringUtils.isNotBlank(req.getOrderName())) {
                list.add(criteriaBuilder.like(root.get("orderName"), "%" + req.getOrderName() + "%"));
            }
            //订单时间
            if (null != req.getState()) {
                list.add(criteriaBuilder.equal(root.get("state"), req.getState()));
            }
            //产品种类
            if (null != req.getType()) {
                list.add(criteriaBuilder.equal(root.get("type"), req.getType()));
            }
            //手机号
            if (StringUtils.isNotBlank(req.getMobile())) {
                list.add(criteriaBuilder.equal(root.get("mobile"), req.getMobile()));
            }
            //######################add 2021-11-20#########################
            if (null != req.getActivityType()){
                list.add(criteriaBuilder.equal(root.get("activityType"), req.getActivityType()));
            }
            if (StringUtils.isNotBlank(req.getActivityName())){
                list.add(criteriaBuilder.like(root.get("activityName"), "%"+req.getActivityName()+"%"));
            }
            //###################################
            try {
                //订单时间
                if (StringUtils.isNotBlank(req.getStartTime())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("orderTime"), sdf.parse(req.getStartTime())));
                }
                if (StringUtils.isNotBlank(req.getEndTime())) {
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("orderTime"), sdf.parse(req.getEndTime())));
                }

            }catch (Exception e) {
                log.error("日期格式化Exception:" + e.getMessage());
            }

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<OrderRecord> orderList = orderRepository.findAll(specification,sort);
        List<OrderExcelResp> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderList)) {
            result = EntityUtils.dtoList2PojoList(orderList, OrderExcelResp.class);
        }
        log.info("销售明细导出报表，result: {}", result.size());
        /** 1. 获取拼接数组集合 **/
        String[] keys = ExcelUtil.ORDER_ITEM_KEYS;
        String[] columnNames = ExcelUtil.ORDER_ITEM_COLUMNNAMES;
        List<Map<String, Object>> exlItemList = ExcelUtil.setFirstItems(ExcelUtil.ORDER_ITEM_SHEET_NAME);
        result.forEach(shareItem -> {
            Map<String, Object> map_i = new HashMap<>(1);
            for (int i = 0; i < keys.length; i++) {
                String fieldValue = ExcelUtil.getFieldValue(shareItem, keys[i] + "");
                if (keys[i].equals("activityType") && StringUtils.isNotBlank(fieldValue)){
                    map_i.put(keys[i], "0".equals(fieldValue)?"积分兑礼":"营销活动");
                }else{
                    map_i.put(keys[i], fieldValue);
                }

            }
            exlItemList.add(map_i);
        });

        /*** 2. 创建workbook **/
        Workbook workbook = ExcelUtil.createWorkBook(exlItemList, keys, columnNames);
        log.info("# [销售明细exls]总记录,count = {}", exlItemList.size());
        return workbook;
    }

    @Override
    public JsonResult coupon(CouponQueryReq req) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Specification<OrderRecord> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //有赞卷  优惠卷
            list.add(criteriaBuilder.notEqual(root.get("type"), 0));
            list.add(criteriaBuilder.equal(root.get("userId"), req.getUserId()));
            if (req.getState().compareTo(2) == 0) {
                list.add(criteriaBuilder.equal(root.get("state"), req.getState()));
            } else {
                list.add(criteriaBuilder.notEqual(root.get("state"), 2));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<OrderRecord> orderList = orderRepository.findAll(specification, sort);
        List<CouponQueryResp> couponQueryRespList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderList)) {
            orderList.forEach(c -> {
                CouponQueryResp couponQueryResp = new CouponQueryResp();
                if (StringUtils.isNotBlank(c.getProductId())) {
                    Product product = productRepository.findOne(c.getProductId());
                    if (null == product)
                        return;
                    //优惠卷
                    if (c.getType().compareTo(2) == 0) {
                        CrmCoupon crmCoupon = crmCouponRepository.findOne(product.getCouponId());
                        if (crmCoupon.getValidType().compareTo(1) == 0) {
                            couponQueryResp.setEndTime(crmCoupon.getEndDate());
                            couponQueryResp.setState(c.getState());
                        }
                        if (crmCoupon.getValidType().compareTo(2) == 0) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(c.getCreateTime());
                            calendar.add(Calendar.DATE, crmCoupon.getValidDays());
                            couponQueryResp.setEndTime(calendar.getTime());
                            couponQueryResp.setState(c.getState());
                        }
                        couponQueryResp.setOrderCode(c.getOrderCode());
                        BeanUtils.copyProperties(product, couponQueryResp);
                        couponQueryRespList.add(couponQueryResp);
                    }
                    //有赞卷
                    if (c.getType().compareTo(1) == 0) {
                            couponQueryResp.setEndTime(product.getOfflineTime());
                            couponQueryResp.setState(c.getState());
                            couponQueryResp.setUrl(product.getUrl());
                            BeanUtils.copyProperties(product, couponQueryResp);
                            couponQueryResp.setOrderCode(c.getOrderCode());
                            couponQueryResp.setCouponId(c.getCouponId());
                            couponQueryRespList.add(couponQueryResp);
                    }
                } else {
                    if (c.getCouponId().compareTo("9333557") == 0 || c.getCouponId().compareTo("9557455") == 0) {
                        List<Coupon> coupons = couponRepository.findByCouponId(c.getCouponId());
                        if (CollectionUtils.isNotEmpty(coupons)) {
                            Coupon coupon = coupons.get(0);
                            couponQueryResp.setState(c.getState());
                            couponQueryResp.setUrl(coupon.getUrl());
                            couponQueryResp.setName(coupon.getCouponName());
                            couponQueryResp.setHeadImage("https://wxadmin.singlemalts.com.cn/group1/M00/01/94/rBOeiF77BRKAc3i9AAAI-Qs5Cjk356_640x10000.jpg");
                            couponQueryResp.setCouponId(c.getCouponId());
                            couponQueryRespList.add(couponQueryResp);
                        }
                    }
                }
            });
        }
        //如果查询所有卷，显示京东天猫卷
//        if (req.getState().compareTo(0) == 0) {
//            CouponQueryResp couponQueryResp1 = new CouponQueryResp();
//            PointQueryReq pointQueryReq = new PointQueryReq();
//            pointQueryReq.setType(-1);
//            pointQueryReq.setCurrentPage("1");
//            pointQueryReq.setPageSize("10");
//            pointQueryReq.setMembershipId(req.getMembershipId());
//            JsonResult jsonResult = taskService.pointList(pointQueryReq);
//            PointQueryResp pointQueryResp = (PointQueryResp) jsonResult.getData();
//            if (null != pointQueryResp) {
//                List<PointListDTO> pointListDTOS = pointQueryResp.getRows();
//                if (CollectionUtils.isNotEmpty(pointListDTOS)) {
//                    //1天猫  2京东
//                    pointListDTOS.stream().filter(d -> d.getSourceType().compareTo(1) == 0 || d.getSourceType().compareTo(2) == 0).forEach(e -> {
//                        if (e.getSourceType().compareTo(1) == 0) {
//                            //天猫卷
//                            couponQueryResp1.setName("天猫优惠卷");
//                            couponQueryResp1.setStartTime(e.getLastUpdated());
//                            couponQueryResp1.setType(3);
//                            couponQueryResp1.setUrl("https://wechat.singlemalts.com.cn/mpresource/crmfile/tmall.jpg");
//                            couponQueryRespList.add(couponQueryResp1);
//                        } else {
//                            //京东卷
//                            couponQueryResp1.setName("京东优惠卷");
//                            couponQueryResp1.setStartTime(e.getLastUpdated());
//                            couponQueryResp1.setType(3);
//                            couponQueryResp1.setUrl("https://wechat.singlemalts.com.cn/mpresource/crmfile/jindong.jpg");
//                            couponQueryRespList.add(couponQueryResp1);
//                        }
//                    });
//                }
//            }
//        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(couponQueryRespList);
        jsonResult.setState(0);
        return jsonResult;
    }

    @Override
    public void updateCoupon(String req) {
        Specification<OrderRecord> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //有赞卷  优惠卷
            list.add(criteriaBuilder.notEqual(root.get("type"), 0));
            list.add(criteriaBuilder.equal(root.get("userId"), req));
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<OrderRecord> orderList = orderRepository.findAll(specification);
        if (CollectionUtils.isNotEmpty(orderList)) {
            orderList.forEach(c -> {
                //优惠卷
                if (c.getType().compareTo(2) == 0) {
                    CrmCoupon crmCoupon = crmCouponRepository.findOne(c.getCouponId());
                    if (crmCoupon != null) {
                        if (crmCoupon.getValidType().compareTo(1) == 0) {
                            c.setState(crmCoupon.getEndDate().compareTo(new Date()) < 0 ? 2 : c.getState());
                        }
                        if (crmCoupon.getValidType().compareTo(2) == 0) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(c.getCreateTime());
                            calendar.add(Calendar.DATE, crmCoupon.getValidDays());
                            c.setState(calendar.getTime().compareTo(new Date()) < 0 ? 2 : c.getState());
                        }
                    }
                }
                //有赞卷
                if (c.getType().compareTo(1) == 0) {
                    if (StringUtils.isNotEmpty(c.getCouponId()) && (c.getCouponId().compareTo("9333557") == 0 || c.getCouponId().compareTo("9557455") == 0)) {
                        return;
                    }
                    //有赞卷时间按照产品时间
                    Product product = productRepository.findOne(c.getProductId());
                    c.setState(product.getOfflineTime().compareTo(new Date()) < 0 ? 2 : c.getState());
                }
            });
            orderRepository.save(orderList);
        }
    }

    @Override
    public List<OrderRecord> findOrderByUserId(String unionId) {
        List<OrderRecord> orderRecords = orderRepository.findByUserId(unionId);
        return orderRecords;
    }

    @Override
    public List<OrderRecord> findNoWechatOrderByUserId(String unionId) {
        return orderRepository.findNoWechatOrderByUserId(unionId);
    }


    private PageImpl cover(OrderQueryReq req) {
        int currentPage = (req.getCurrentPage() - 1) < 0 ? 0 : req.getCurrentPage() - 1;
        int pageSize = req.getPageSize() < 1 ? 10 : req.getPageSize();
        Pageable pageable = new PageRequest(currentPage, pageSize, new Sort(Sort.Direction.DESC, "createTime"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Specification<OrderRecord> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //顾客姓名
            if (StringUtils.isNotBlank(req.getName())) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + req.getName() + "%"));
            }
            //产品名字
            if (StringUtils.isNotBlank(req.getOrderName())) {
                list.add(criteriaBuilder.like(root.get("orderName"), "%" + req.getOrderName() + "%"));
            }
            //订单时间
            if (null != req.getState()) {
                list.add(criteriaBuilder.equal(root.get("state"), req.getState()));
            }
            //产品种类
            if (null != req.getType()) {
                list.add(criteriaBuilder.equal(root.get("type"), req.getType()));
            }
            //手机号
            if (StringUtils.isNotBlank(req.getMobile())) {
                list.add(criteriaBuilder.equal(root.get("mobile"), req.getMobile()));
            }
            //######################add 2021-11-20 添加 活动类型、活动名称条件查询#########################
            if (null != req.getActivityType()){
                list.add(criteriaBuilder.equal(root.get("activityType"), req.getActivityType()));
            }
            if (StringUtils.isNotBlank(req.getActivityName())){
                list.add(criteriaBuilder.like(root.get("activityName"), "%"+req.getActivityName()+"%"));
            }
            //###################################
            try {
                //订单时间
                if (StringUtils.isNotBlank(req.getStartTime())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("orderTime"), sdf.parse(req.getStartTime())));
                }
                if (StringUtils.isNotBlank(req.getEndTime())) {
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("orderTime"), sdf.parse(req.getEndTime())));
                }

            }catch (Exception e) {
                log.error("日期格式化Exception:" + e.getMessage());
            }

            //小程序查询类型标识 zhaoyul
            if (StringUtils.isNotBlank(req.getWxDeliverType())) {
                //已发货 物流编号不为空
                if ("2".equals(req.getWxDeliverType())) {
                  //  list.add(criteriaBuilder.isNotNull(root.get("logisticsCodeErp")));
                    Predicate logisticsCodeErp = criteriaBuilder.isNotNull(root.get("logisticsCodeErp"));
                    Predicate orderType = criteriaBuilder.equal(root.get("orderType"), "10");
                    //满足 物流编号不为空 或者是积分订单已发货
                    list.add(criteriaBuilder.or(logisticsCodeErp,orderType));
                } else if ("1".equals(req.getWxDeliverType())) {
                    //未发货 物流编号为空
                    list.add(criteriaBuilder.isNull(root.get("logisticsCodeErp")));
                } else {
                    //查询全部
                }

            }
            //订单类型
            if (StringUtils.isNotBlank(req.getOrderType())) {
                list.add(criteriaBuilder.equal(root.get("orderType"),req.getOrderType()));
            }
            if (null != req.getLogisticsPushState()) {
                list.add(criteriaBuilder.equal(root.get("logisticsPushState"),req.getLogisticsPushState()));
            }
            //用户权限
            if (StringUtils.isNotBlank(req.getMembershipId())) {
                list.add(criteriaBuilder.equal(root.get("membershipId"),req.getMembershipId()));
            }

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page page = orderRepository.findAll(specification, pageable);
        List<OrderRecord> orderList = page.getContent();
        List<OrderResp> orderRespList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderList)) {
            orderRespList = EntityUtils.dtoList2PojoList(orderList, OrderResp.class);

            //orderRespList = orderRespList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getProductId()))), ArrayList::new));


            //将订单中所有用户unionId去重，封装到list
            Set<String> collect = orderRespList.stream().map(OrderResp::getUserId).collect(Collectors.toSet());
            List<Member> allMemberList = new ArrayList<>();
            if(collect !=null && collect.size() >0){
//                List<String> result = new ArrayList<>(collect);
                //数据量较大,超过1000条，分组in查询
//               if(collect.size() >1000) {
//                   List<List<String>> groupMemberList = com.google.common.collect.Lists.partition(result, 1000);
//                   List<Member> memberList = null;
//                   for (List<String> list : groupMemberList) {
//                       memberList = memberRepository.findByUserIds(list);
//                       //将分批次查询到的数据组合
//                       allMemberList.addAll(memberList);
//                   }
//               }else{
                    allMemberList = memberRepository.findByUserIds(new ArrayList<>(collect));
//               }
          }
            Map<String, Member> memberMap = allMemberList.stream().collect(Collectors.toMap(Member::getUnionId, x -> x));
            Member member = null;
            for (OrderResp o:orderRespList) {
                member =memberMap.get(o.getUserId());
                if(member !=null){
                    if(StringUtils.isNotEmpty(member.getMobile())){
                        o.setMemberMobile(member.getMobile());
                    }
                    o.setNickName(member.getNickName());
                    o.setHeadImgUrl(member.getHeadImgUrl());
                }

                if(null != o.getPoints()) {
                    o.setPointCount(o.getCount() * o.getPoints());
                }
                if (null != o && StringUtils.isBlank(o.getProductId())) {
                    String couponId = o.getCouponId();
                    o.setCount(1);
                    if (couponId.compareTo("9333557") == 0 || couponId.compareTo("9557455") == 0) {
                        List<Coupon> coupons = couponRepository.findByCouponId(o.getCouponId());
                        if (CollectionUtils.isNotEmpty(coupons)) {
                            Coupon coupon = coupons.get(0);
                            o.setOrderName(coupon.getCouponName());
                            o.setHeadImgUrl("https://wxadmin.singlemalts.com.cn/group1/M00/01/94/rBOeiF77BRKAc3i9AAAI-Qs5Cjk356_640x10000.jpg");
                        }
                    }
                }

            }
        }
        PageImpl<OrderResp> pageTasks = new PageImpl<>(orderRespList, pageable, page.getTotalElements());
        return pageTasks;
    }

    public List<CouponCrmDTO> couponList() {
        String accessToken = accessTokenImpl.getAccessToken();
        String requestUrl = Constants.CouponList.replace("ACCESSTOKEN", accessToken);
        String result = restTemplate.getForEntity(requestUrl, String.class).getBody();
        Object rows = JSON.parseObject(result, Map.class).get("rows");
        List<CouponCrmDTO> couponCrmDTOS = JSONObject.parseArray(JSON.toJSONString(rows), CouponCrmDTO.class);
        return couponCrmDTOS;
    }

    private String getOrderCode() {
        Random random = new Random();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String correntTime = simpleDateFormat.format(new Date());
        String result = "N" + correntTime + random.nextInt(10);
        return result;
    }

    @Override
    public List<CouponQueryResp> solvedOrderRecord(List<OrderRecord> orderList){
        List<CouponQueryResp> couponQueryRespList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderList)) {
            orderList.forEach(c -> {
                CouponQueryResp couponQueryResp = new CouponQueryResp();
                if (org.apache.commons.lang.StringUtils.isNotBlank(c.getProductId())) {
                    Product product = productRepository.findOne(c.getProductId());
//                    if (null == product)
//                        return;
                    //优惠卷
                    if (c.getType().compareTo(2) == 0) {
                        if(c.getCouponId()!=null){
                            CrmCoupon crmCoupon = crmCouponRepository.findOne(c.getCouponId());
                            if (crmCoupon.getValidType().compareTo(1) == 0) {
                                couponQueryResp.setEndTime(crmCoupon.getEndDate());
                                couponQueryResp.setState(c.getState());
                            }
                            if (crmCoupon.getValidType().compareTo(2) == 0) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(c.getCreateTime());
                                calendar.add(Calendar.DATE, crmCoupon.getValidDays());
                                couponQueryResp.setEndTime(calendar.getTime());
                                couponQueryResp.setState(c.getState());
                            }
                            couponQueryResp.setOrderCode(c.getOrderCode());
                            if(product !=null){
                                BeanUtils.copyProperties(product, couponQueryResp);
                            }
                        }
                        couponQueryRespList.add(couponQueryResp);
                    }
                    //有赞卷
                    if (c.getType().compareTo(1) == 0) {
                        if(product !=null) {
                            couponQueryResp.setEndTime(product.getOfflineTime());
                            couponQueryResp.setUrl(product.getUrl());
                            BeanUtils.copyProperties(product, couponQueryResp);
                        }
                        couponQueryResp.setState(c.getState());
                        couponQueryResp.setOrderCode(c.getOrderCode());
                        couponQueryResp.setCouponId(c.getCouponId());
                        couponQueryRespList.add(couponQueryResp);
                    }
                } else {
                    if (c.getCouponId().compareTo("9333557") == 0 || c.getCouponId().compareTo("9557455") == 0) {
                        List<Coupon> coupons = couponRepository.findByCouponId(c.getCouponId());
                        if (CollectionUtils.isNotEmpty(coupons)) {
                            Coupon coupon = coupons.get(0);
                            couponQueryResp.setState(c.getState());
                            couponQueryResp.setUrl(coupon.getUrl());
                            couponQueryResp.setName(coupon.getCouponName());
                            couponQueryResp.setHeadImage("https://wxadmin.singlemalts.com.cn/group1/M00/01/94/rBOeiF77BRKAc3i9AAAI-Qs5Cjk356_640x10000.jpg");
                            couponQueryResp.setCouponId(c.getCouponId());
                            couponQueryRespList.add(couponQueryResp);
                        }
                    }
                }
            });
        }
        return couponQueryRespList;
    }

    @Override
    public Member getMemberDetails(String membershipId) {
        return  memberRepository.findByUnionId(membershipId);
    }

    /**
     * 创建实物券订单
     * @param req
     * @return
     */
    @Override
    public JsonResult savePhysicalVoucher(OrderReq req) {
        log.info("创建实物券订单入参: {}", JSON.toJSONString(req));
        JsonResult jsonResult = new JsonResult();
        Integer key = req.getPrizeGoodId();
        Boolean resultRedis = redisUtils.setIfAbsent(String.valueOf(key), key);
        log.info("resultRedis={}", resultRedis);
        try {
            if (resultRedis) {
                // 查询奖品信息
                log.info("查询奖品信息入参: {}", JSON.toJSONString(req.getPrizeGoodId()));
                PrizeGood prizeGood = prizeGoodRepository.findOne(req.getPrizeGoodId());
                log.info("查询奖品信息返回: {}", JSON.toJSONString(prizeGood));

                // 扣减后的新库存 todo 助力活动时已扣减库存 这里重复扣减了
               /* Integer stock = prizeGood.getStock() - req.getCount();
                log.info("扣减后的新库存: {}", stock);

                // 库存校验
                if (prizeGood.getStock().compareTo(req.getCount()) < 0) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("库存不足，无法兑换");
                    return jsonResult;
                }*/

                // 获取当前时间(UTC格式)
                Date currentTime = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentTime);
                calendar.add(Calendar.HOUR, -8);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                String timeStamp = formatter.format(calendar.getTime());

                // 封装订单数据
                OrderRecord order = new OrderRecord();
                BeanUtils.copyProperties(req, order);
                order.setOrderCode(getOrderCode());
                order.setImageUrl(prizeGood.getGoodImg());
                order.setState(0);
                order.setType(0);
                order.setOrderTime(new Date());
                order.setCreateTime(new Date());
                order.setUpdateTime(new Date());
                order.setProductId(String.valueOf(prizeGood.getId()));
                order.setLogisticsAddress(req.getLogisticsAddress());
                order.setOrderType(OrderTypeEnum.ORDER_TYPE_20.getCode());
                // 用来判断是否是卡券实物订单
                order.setGoodType("1");
                // 用来判断是否是卡券实物订单
                order.setPrizeId(req.getPrizeId());
                //添加下发物流状态
                order.setLogisticsPushState(LogisticsPushStateEnum.LOGISTICS_PUSH_10.getCode());
                order.setSkuId(prizeGood.getSpecNo());
                //add 2021-11-29 添加订单类型和订单活动
                wrapOrder(order,req);
                log.info("创建实物券订单入参:{}", JSON.toJSONString(order));
                order = orderRepository.saveAndFlush(order);
                log.info("创建实物券订单返回:{}", JSON.toJSONString(order));
                OrderResp orderResp = new OrderResp();
                BeanUtils.copyProperties(order, orderResp);
                OrderCreateResp orderCreateResp = new OrderCreateResp();
                orderCreateResp.setOrderResp(orderResp);

                // 判断是否为第一次兑换,是:添加积分
                List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(req.getUserId(),12);
                if(list == null || list.size() ==0){
                    TaskRecord taskRecord = new TaskRecord();
                    taskRecord.setCreateTime(new Date());
                    taskRecord.setTaskType(12);
                    taskRecord.setUserId(req.getUserId());
                    taskRecordRepository.save(taskRecord);
                    log.info("本地第一次积分兑礼添加积分完成");
                    String requestUrl1 = Constants.PointIncr
                        .replace("MEMBERSHIP", req.getMembershipId())
                        .replace("ACCESSTOKEN", accessTokenImpl.getAccessToken());
                    PointDTO dto = new PointDTO();
                    dto.setContentName("第一次兑换赠送积分");
                    dto.setSource("帝亚吉欧会员俱乐部");
                    dto.setDate(timeStamp);
                    dto.setPattern(1);//第一次积分兑礼
                    dto.setPoint(20);
                    OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                    okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
                    Request request = new Request.Builder()
                        .url(requestUrl1)
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                    try {
                        Response response = client.newCall(request).execute();
                        String jsresult = new String(response.body().bytes());
                        log.info("调用加分接口,返回值:{}", jsresult);
                        response.body().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // 更新库存 todo 助力活动时已扣减库存 这里重复扣减了
               /* log.info("更新库存入参: 新stock={}, 旧stock={}, prizeGoodId={}", stock, prizeGood.getStock(), prizeGood.getId());
                Integer update = prizeGoodRepository.updateStock(stock, prizeGood.getStock(), prizeGood.getId());
                log.info("更新库存返回: {}", update);
                if (update < 1) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("系统异常，请重新兑换");
                    return jsonResult;
                }*/

                jsonResult.setState(0);
                jsonResult.setData(orderCreateResp);
                redisUtils.remove(String.valueOf(key));
            } else {
                jsonResult.setState(1);
                jsonResult.setMessage("系统异常，请重试");
            }
        } catch (RestClientException e) {
            redisUtils.remove(String.valueOf(key));
            jsonResult.setState(1);
            jsonResult.setMessage("系统异常，请重试");
        } finally {
            redisUtils.remove(String.valueOf(key));
        }
        return jsonResult;
    }

    @Override
    public void updateOrderLogisState(OrderRecord orderRecord) {
        OrderRecord order = orderRepository.findByOrderCode(orderRecord.getOrderCode());
        order.setLogisticsPushState(orderRecord.getLogisticsPushState());
        orderRepository.saveAndFlush(order);
    }

    @Override
    public OrderRecord queryOrderDetails(String orderCode) {

        return orderRepository.findByOrderCode(orderCode);
    }

    @Override
    public void updateOrderDetails(OrderRecord object) {
        orderRepository.saveAndFlush(object);
    }


    @Override
    public List<OrderRecord> getOrderOneByCarRoll(String userId,String prizeGoodId) {
        return orderRepository.findOrderOneByCarRoll(userId,prizeGoodId);
    }

    @Override
    public List<OrderRecord> getOrderOneByCarRollPrizeId(String userId, String prizeGoodId, Integer prizeId) {
        return orderRepository.findOrderOneByCarRollPrizeId(userId,prizeGoodId,prizeId);
    }




    //################################add by zdc 2021-22-19###########################
    private void wrapOrder(OrderRecord order,OrderReq req){
        if (null != req.getPrizeId()){
            Prize prize = this.prizeRepository.findOne(req.getPrizeId());
            if (null != prize){
                DrawActivity drawActivity = this.drawActivityRepository.findOne(prize.getActivityId());
                order.setActivityType(1);
                order.setActivityId(prize.getActivityId());
                order.setActivityName(drawActivity==null?null:drawActivity.getActivityName());
            }
        }
    }


    @Override
    public JsonResult subStock(OrderReq req) {
        JsonResult jsonResult = new JsonResult();
        String key = req.getProductId();
        Boolean resultRedis = redisUtils.setIfAbsent(key, key);
        log.info("resultRedis={}", resultRedis);
        List<OrderRecord> orderRecordResult = new ArrayList<OrderRecord>();
        try {
            if (resultRedis) {
                //判断会员等级
                // Product product = productRepository.findOne(req.getProductId());
                OrderRecord order ;
                List<Product> productListByName = productRepository.getProductListByName(req.getOrderName());

                for (Product product : productListByName) {

                //库存校验--
                if (product.getStock().compareTo(req.getCount()) < 0) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("库存不足，无法兑换");
                    return jsonResult;
//                    continue;
                }
                //1有赞卷每个人只可以兑换一次
                if (product.getType().compareTo(1) == 0) {
                    List<OrderRecord> orderRecords = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                    if (CollectionUtils.isNotEmpty(orderRecords)) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("该产品每人只可兑换一次，无法重复兑换");
                        return jsonResult;
                    }
                }
                // 2优惠卷
                if (product.getType().compareTo(2) == 0) {
                    //查询优惠卷库存
                    CrmCoupon crmCoupon = crmCouponRepository.findOne(product.getCouponId());
                    if (null == crmCoupon) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("优惠券异常，请联系管理员");
                        return jsonResult;
                    }
                    //库存校验
                    if (crmCoupon.getStore().compareTo(req.getCount()) < 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("优惠券库存不足，无法兑换");
                        return jsonResult;
                    }
                    //查询改优惠卷顾客兑换次数
                    List<OrderRecord> orderRecordList = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                    String count = String.valueOf(orderRecordList.size());
                    if (crmCoupon.getDrawLimit().compareTo(count) <= 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("该优惠券已达兑换上限，无法兑换");
                        return jsonResult;
                    }
                }
                //乐观锁更新库存---
                Integer stock = product.getStock() - req.getCount();

                Integer update = productRepository.updateStock(stock, product.getStock(), product.getId());
                if (update < 1) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("系统异常，请重新兑换");
                    return jsonResult;
                }
                //扣取积分
                String accessToken = accessTokenImpl.getAccessToken();
                String requestUrl = Constants.PointDecr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                log.info("requestUrl={}", requestUrl);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                Date currentTime = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentTime);
                calendar.add(Calendar.HOUR, -8);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                String timeStamp = formatter.format(calendar.getTime());
                //调用微信请求实体
                Integer countPoints = product.getPoints() * req.getCount();
                PointDTO pointDTO = new PointDTO();
                pointDTO.setPoint(countPoints);
                pointDTO.setContentName(product.getName());
                pointDTO.setDate(timeStamp);
                pointDTO.setPattern(1);//互动积分传值"3"，积分兑换传值"1"
                //remark 存放头像  和订单号
                String getOrderCode = getOrderCode();//订单号
                String getHeadImage = StringUtils.isNotBlank(product.getHeadImage()) ? product.getHeadImage() : null;
                Map<String, Object> map = new HashMap<>();
                map.put("orderCode", getOrderCode);
                map.put("headImage", getHeadImage);
                pointDTO.setRemark(JSON.toJSONString(map));
                pointDTO.setSource("帝亚吉欧会员俱乐部");
                HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(pointDTO), headers);
                JSONObject result = restTemplate.postForObject(requestUrl, httpEntity, JSONObject.class);
                log.info("积分兑换返回信息: {}", result.toString());
                Object error = result.getJSONObject("error");
                if (null != error) {
                    log.info("调用crm接口返回error!");
                    CrmErrorDTO crmErrorDTO = JSON.parseObject(JSON.toJSONString(error), CrmErrorDTO.class);
                    log.info("积分兑换异常返回信息: {}", crmErrorDTO.toString());
                    //添加库存   remove分布式锁
                    productRepository.updateStock(product.getStock(), stock, product.getId());
                    redisUtils.remove(key);
                    if (crmErrorDTO.getCode().compareTo("409180") == 0) {
                        jsonResult.setState(1);
                        jsonResult.setData(crmErrorDTO);
                        jsonResult.setMessage("积分不足，无法兑换");
                        return jsonResult;
                    }
                    jsonResult.setState(1);
                    jsonResult.setData(crmErrorDTO);
                    jsonResult.setMessage("积分兑换异常，请重新尝试");
                    return jsonResult;
                }
                PointDTO pointDto = JSON.parseObject(JSON.toJSONString(result), PointDTO.class);
                //优惠卷需要分配couponId
                 order  = new OrderRecord();
                if (0==product.getType()) {
                    // 实物
                    order.setState(0);
                    order.setOrderType(OrderTypeEnum.ORDER_TYPE_20.getCode());
                } else {
                    order.setState(1);
                    // 有赞券 微信券
                    order.setOrderType(OrderTypeEnum.ORDER_TYPE_10.getCode());
                    order.setCouponId(product.getCouponId());
                }  //  Cannot find local variable 'productRespList'
                BeanUtils.copyProperties(req, order);
                order.setOrderCode(getOrderCode);
                order.setType(product.getType());
                order.setOrderTime(new Date());
                order.setCreateTime(new Date());
                order.setUpdateTime(new Date());
                //添加下发物流状态
                order.setLogisticsPushState(LogisticsPushStateEnum.LOGISTICS_PUSH_10.getCode());
                //设置订单总积分
                order.setPoints(product.getPoints());
                //物流地址
                order.setLogisticsAddress(req.getLogisticsAddress());
                if(StringUtils.isNotEmpty(req.getSkuId())){
                    order.setSkuId(req.getSkuId());
                }
                orderRecordResult.add(order);
                //order = orderRepository.saveAndFlush(order);
                OrderResp orderResp = new OrderResp();
                BeanUtils.copyProperties(order, orderResp);
                OrderCreateResp orderCreateResp = new OrderCreateResp();
                orderCreateResp.setOrderResp(orderResp);
                orderCreateResp.setPointDTO(pointDto);
                List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(req.getUserId(),12);
                if(list == null || list.size() == 0){
                    TaskRecord taskRecord = new TaskRecord();
                    taskRecord.setCreateTime(new Date());
                    taskRecord.setTaskType(12);
                    taskRecord.setUserId(req.getUserId());
                    taskRecordRepository.save(taskRecord);
                    log.info("本地第一次积分兑礼添加积分完成");
                    String requestUrl1 = Constants.PointIncr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                    PointDTO dto = new PointDTO();
                    dto.setContentName("第一次兑换赠送积分");
                    dto.setSource("帝亚吉欧会员俱乐部");
                    dto.setDate(timeStamp);
                    dto.setPattern(1);//第一次积分兑礼
                    dto.setPoint(20);
                    OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                    okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
                    Request request = new Request.Builder()
                        .url(requestUrl1)
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                    try {
                        Response response = client.newCall(request).execute();
                        String jsresult = new String(response.body().bytes());
                        log.info("调用加分接口,返回值:{}", jsresult);
                        response.body().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                jsonResult.setState(0);
                jsonResult.setData(orderCreateResp);
                redisUtils.remove(key);
                };

            } else {
                jsonResult.setState(1);
                jsonResult.setMessage("系统异常，请重试");
            }
        } catch (RestClientException e) {
            redisUtils.remove(key);
            jsonResult.setState(1);
            jsonResult.setMessage("系统异常，请重试");
        } finally {
            //生成订单(商品名字一样，只生成一个订单)----可能会有问题(防止上边返回结果里拿不到的数据)***
            if (CollectionUtils.isNotEmpty(orderRecordResult)){
                OrderRecord orderRecord = orderRepository.saveAndFlush(orderRecordResult.get(0));
                OrderResp orderResp = new OrderResp();
                BeanUtils.copyProperties(orderRecord, orderResp);
                OrderCreateResp orderCreateResp = new OrderCreateResp();
                orderCreateResp.setOrderResp(orderResp);
                jsonResult.setData(orderCreateResp);
            }
            redisUtils.remove(key);
        }
        return jsonResult;
    }


    /*    @Override
    public JsonResult save(OrderReq req) {
        JsonResult jsonResult = new JsonResult();
        String key = req.getProductId();
        Boolean resultRedis = redisUtils.setIfAbsent(key, key);
        log.info("resultRedis={}", resultRedis);
        try {
            if (resultRedis) {
                //判断会员等级
                Product product = productRepository.findOne(req.getProductId());
                //库存校验
                if (product.getStock().compareTo(req.getCount()) < 0) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("库存不足，无法兑换");
                    return jsonResult;
                }
                //1有赞卷每个人只可以兑换一次
                if (product.getType().compareTo(1) == 0) {
                    List<OrderRecord> orderRecords = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                    if (CollectionUtils.isNotEmpty(orderRecords)) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("该产品每人只可兑换一次，无法重复兑换");
                        return jsonResult;
                    }
                }
                // 2优惠卷
                if (product.getType().compareTo(2) == 0) {
                    //查询优惠卷库存
//                    List<CouponCrmDTO> couponCrmDTOS = couponList();
//                    Map<String, CouponCrmDTO> map = couponCrmDTOS.stream().collect(Collectors.toMap(CouponCrmDTO::getCouponId, c -> c));
//                    CouponCrmDTO couponCrmDTO = map.get(product.getCouponId());

                    CrmCoupon crmCoupon = crmCouponRepository.findOne(product.getCouponId());

                    if (null == crmCoupon) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("优惠券异常，请联系管理员");
                        return jsonResult;
                    }
                    //库存校验
                    if (crmCoupon.getStore().compareTo(req.getCount()) < 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("优惠券库存不足，无法兑换");
                        return jsonResult;
                    }
                    //查询改优惠卷顾客兑换次数
                    List<OrderRecord> orderRecordList = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                    String count = String.valueOf(orderRecordList.size());
                    if (crmCoupon.getDrawLimit().compareTo(count) <= 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("该优惠券已达兑换上限，无法兑换");
                        return jsonResult;
                    }
                }

                if (0 == product.getType()&&!"0".equals(product.getLimitPerperson())) {
                    List<OrderRecord> orderRecords = orderRepository.findByUserIdAndProductName(req.getUserId(), product.getName());
                    //限兑类型（1按月限兑、2按年限兑）product.getLimitType()
                    // 每位会员限兑件数（0表示不限兑）product.getLimitPerperson();
                    if ("1".equals(product.getLimitType())) {
                        long count = orderRecords.stream().filter(orderRecord -> {

                            Date date = new Date();
                            int orderTime = DateUtils.getYearMonth(orderRecord.getCreateTime());
                            int sysTime = DateUtils.getYearMonth(date);
                            if (sysTime == orderTime) {
                                return true;
                            }
                            return false;
                        }).mapToInt(OrderRecord::getCount).sum();
                        Long perperson = Long.valueOf(product.getLimitPerperson());
                        if (perperson - count == 0){
                            jsonResult.setState(-1);
                            jsonResult.setMessage("本月您已兑换了该产品的最大限兑数量"+product.getLimitPerperson()+"件，不可再兑换该产品");
                            return jsonResult;
                        } else if (perperson - count > 0) {

                            long val = perperson - (count+Long.valueOf(req.getCount()));
                            if (val<0) {
                                jsonResult.setState(-1);
                                jsonResult.setMessage("您已超过了该产品的最大可兑换数量"+product.getLimitPerperson()+"件，请重新确认");
                                return jsonResult;
                            }
                            log.info("正常执行兑换");
                        } else {
                            jsonResult.setState(-1);
                            jsonResult.setMessage("本月您已兑换了该产品的最大限兑数量"+product.getLimitPerperson()+"件，不可再兑换该产品");
                            return jsonResult;
                        }

                    }else if ("2".equals(product.getLimitType())) {
                        long count = orderRecords.stream().filter(orderRecord -> {

                            Date date = new Date();
                            int orderTime = DateUtils.getYear(orderRecord.getCreateTime());
                            int sysTime = DateUtils.getYear(date);
                            if (sysTime == orderTime) {
                                return true;
                            }
                            return false;
                        }).mapToInt(OrderRecord::getCount).sum();
                        Long perperson = Long.valueOf(product.getLimitPerperson());
                        if (perperson - count == 0){
                            jsonResult.setState(-1);
                            jsonResult.setMessage("本年度您已兑换了该产品的最大限兑数量"+product.getLimitPerperson()+"件，不可再兑换该产品");
                            return jsonResult;
                        } else if (perperson - count > 0) {

                            long val = perperson - (count+Long.valueOf(req.getCount()));
                            if (val<0) {
                                jsonResult.setState(-1);
                                jsonResult.setMessage("本年度您已超过了该产品的最大可兑换数量"+product.getLimitPerperson()+"件，请重新确认");
                                return jsonResult;
                            }
                            log.info("正常执行兑换");
                        } else {
                            jsonResult.setState(-1);
                            jsonResult.setMessage("本年度您已兑换了该产品的最大限兑数量"+product.getLimitPerperson()+"件，不可再兑换该产品");
                            return jsonResult;
                        }
                    } else {
                        log.info("未设置类型LimitType :{}",product.getLimitType());
                    }
                }
                //乐观锁更新库存
                Integer stock = product.getStock() - req.getCount();
                Integer update = productRepository.updateStock(stock, product.getStock(), product.getId());
                if (update < 1) {
                    jsonResult.setState(1);
                    jsonResult.setMessage("系统异常，请重新兑换");
                    return jsonResult;
                }
                //扣取积分
                String accessToken = accessTokenImpl.getAccessToken();
                String requestUrl = Constants.PointDecr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                log.info("requestUrl={}", requestUrl);
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                Date currentTime = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentTime);
                calendar.add(Calendar.HOUR, -8);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                String timeStamp = formatter.format(calendar.getTime());
                //调用微信请求实体
                Integer countPoints = product.getPoints() * req.getCount();
                PointDTO pointDTO = new PointDTO();
                pointDTO.setPoint(countPoints);
                pointDTO.setContentName(product.getName());
                pointDTO.setDate(timeStamp);
                pointDTO.setPattern(1);//互动积分传值"3"，积分兑换传值"1"
                //remark 存放头像  和订单号
                String getOrderCode = getOrderCode();//订单号
                String getHeadImage = StringUtils.isNotBlank(product.getHeadImage()) ? product.getHeadImage() : null;
                Map<String, Object> map = new HashMap<>();
                map.put("orderCode", getOrderCode);
                map.put("headImage", getHeadImage);
                pointDTO.setRemark(JSON.toJSONString(map));
                pointDTO.setSource("帝亚吉欧会员俱乐部");
                HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(pointDTO), headers);
                JSONObject result = restTemplate.postForObject(requestUrl, httpEntity, JSONObject.class);
                log.info("积分兑换返回信息: {}", result.toString());
                Object error = result.getJSONObject("error");
                if (null != error) {
                    log.info("调用crm接口返回error!");
                    CrmErrorDTO crmErrorDTO = JSON.parseObject(JSON.toJSONString(error), CrmErrorDTO.class);
                    log.info("积分兑换异常返回信息: {}", crmErrorDTO.toString());
                    //添加库存   remove分布式锁
                    productRepository.updateStock(product.getStock(), stock, product.getId());
                    redisUtils.remove(key);
                    if (crmErrorDTO.getCode().compareTo("409180") == 0) {
                        jsonResult.setState(1);
                        jsonResult.setData(crmErrorDTO);
                        jsonResult.setMessage("积分不足，无法兑换");
                        return jsonResult;
                    }
                    jsonResult.setState(1);
                    jsonResult.setData(crmErrorDTO);
                    jsonResult.setMessage("积分兑换异常，请重新尝试");
                    return jsonResult;
                }
                PointDTO pointDto = JSON.parseObject(JSON.toJSONString(result), PointDTO.class);
                //优惠卷需要分配couponId
                OrderRecord order = new OrderRecord();
                if (0==product.getType()) {
                    // 实物
                    order.setState(0);
                    order.setOrderType(OrderTypeEnum.ORDER_TYPE_20.getCode());
                } else {
                    order.setState(1);
                    // 有赞券 微信券
                    order.setOrderType(OrderTypeEnum.ORDER_TYPE_10.getCode());
                    order.setCouponId(product.getCouponId());
                }
                BeanUtils.copyProperties(req, order);
                order.setOrderCode(getOrderCode);

                order.setType(product.getType());
                order.setOrderTime(new Date());
                order.setCreateTime(new Date());
                order.setUpdateTime(new Date());
                //添加下发物流状态
                order.setLogisticsPushState(LogisticsPushStateEnum.LOGISTICS_PUSH_10.getCode());
                //设置订单总积分 zhaoyl
                order.setPoints(product.getPoints());
                //物流地址
                order.setLogisticsAddress(req.getLogisticsAddress());
                if(StringUtils.isNotEmpty(req.getSkuId())){
                    order.setSkuId(req.getSkuId());
                }
                order = orderRepository.saveAndFlush(order);
                OrderResp orderResp = new OrderResp();
                BeanUtils.copyProperties(order, orderResp);
                OrderCreateResp orderCreateResp = new OrderCreateResp();
                orderCreateResp.setOrderResp(orderResp);
                orderCreateResp.setPointDTO(pointDto);
                List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(req.getUserId(),12);
                if(list == null || list.size() == 0){
                    TaskRecord taskRecord = new TaskRecord();
                    taskRecord.setCreateTime(new Date());
                    taskRecord.setTaskType(12);
                    taskRecord.setUserId(req.getUserId());
                    taskRecordRepository.save(taskRecord);
                    log.info("本地第一次积分兑礼添加积分完成");
                    String requestUrl1 = Constants.PointIncr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                    PointDTO dto = new PointDTO();
                    dto.setContentName("第一次兑换赠送积分");
                    dto.setSource("帝亚吉欧会员俱乐部");
                    dto.setDate(timeStamp);
                    dto.setPattern(1);//第一次积分兑礼
                    dto.setPoint(20);
                    OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                    okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
                    Request request = new Request.Builder()
                        .url(requestUrl1)
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                    try {
                        Response response = client.newCall(request).execute();
                        String jsresult = new String(response.body().bytes());
                        log.info("调用加分接口,返回值:{}", jsresult);
                        response.body().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                jsonResult.setState(0);
                jsonResult.setData(orderCreateResp);
                redisUtils.remove(key);
            } else {
                jsonResult.setState(1);
                jsonResult.setMessage("系统异常，请重试");
            }
        } catch (RestClientException e) {
            redisUtils.remove(key);
            jsonResult.setState(1);
            jsonResult.setMessage("系统异常，请重试");
        } finally {
            redisUtils.remove(key);
        }
        return jsonResult;
    }*/


  /*    public JsonResult save(OrderReq req)  {
        JsonResult jsonResult = new JsonResult();
        String key = req.getProductId();
        Boolean resultRedis = redisUtils.setIfAbsent(key, key);
        log.info("resultRedis={}", resultRedis);
        try {
            if (resultRedis) {
                //判断会员等级
                // Product product = productRepository.findOne(req.getProductId());

                List<Product> productListByName = productRepository.getProductListByName(req.getOrderName());
                for (Product product : productListByName) {
                    //库存校验--
                    if (product.getStock().compareTo(req.getCount()) < 0) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("库存不足，无法兑换");
                        //return jsonResult;
                        continue;
                    }
                    //1有赞卷每个人只可以兑换一次
                    if (product.getType().compareTo(1) == 0) {
                        List<OrderRecord> orderRecords = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                        if (CollectionUtils.isNotEmpty(orderRecords)) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("该产品每人只可兑换一次，无法重复兑换");
                            return jsonResult;
                        }
                    }
                    // 2优惠卷
                    if (product.getType().compareTo(2) == 0) {
                        //查询优惠卷库存
                        CrmCoupon crmCoupon = crmCouponRepository.findOne(product.getCouponId());
                        if (null == crmCoupon) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("优惠券异常，请联系管理员");
                            return jsonResult;
                        }
                        //库存校验
                        if (crmCoupon.getStore().compareTo(req.getCount()) < 0) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("优惠券库存不足，无法兑换");
                            return jsonResult;
                        }
                        //查询改优惠卷顾客兑换次数
                        List<OrderRecord> orderRecordList = orderRepository.findByUserIdAndProductId(req.getUserId(), product.getId());
                        String count = String.valueOf(orderRecordList.size());
                        if (crmCoupon.getDrawLimit().compareTo(count) <= 0) {
                            jsonResult.setState(1);
                            jsonResult.setMessage("该优惠券已达兑换上限，无法兑换");
                            return jsonResult;
                        }
                    }
                    //乐观锁更新库存---
                    Integer stock = product.getStock() - req.getCount();

                    Integer update = productRepository.updateStock(stock, product.getStock(), product.getId());
                    if (update < 1) {
                        jsonResult.setState(1);
                        jsonResult.setMessage("系统异常，请重新兑换");
                        return jsonResult;
                    }
                    //扣取积分
                    String accessToken = accessTokenImpl.getAccessToken();
                    String requestUrl = Constants.PointDecr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                    log.info("requestUrl={}", requestUrl);
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    Date currentTime = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(currentTime);
                    calendar.add(Calendar.HOUR, -8);
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    String timeStamp = formatter.format(calendar.getTime());
                    //调用微信请求实体
                    Integer countPoints = product.getPoints() * req.getCount();
                    PointDTO pointDTO = new PointDTO();
                    pointDTO.setPoint(countPoints);
                    pointDTO.setContentName(product.getName());
                    pointDTO.setDate(timeStamp);
                    pointDTO.setPattern(1);//互动积分传值"3"，积分兑换传值"1"
                    //remark 存放头像  和订单号
                    String getOrderCode = getOrderCode();//订单号
                    String getHeadImage = StringUtils.isNotBlank(product.getHeadImage()) ? product.getHeadImage() : null;
                    Map<String, Object> map = new HashMap<>();
                    map.put("orderCode", getOrderCode);
                    map.put("headImage", getHeadImage);
                    pointDTO.setRemark(JSON.toJSONString(map));
                    pointDTO.setSource("帝亚吉欧会员俱乐部");
                    HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(pointDTO), headers);
                    JSONObject result = restTemplate.postForObject(requestUrl, httpEntity, JSONObject.class);
                    log.info("积分兑换返回信息: {}", result.toString());
                    Object error = result.getJSONObject("error");
                    if (null != error) {
                        log.info("调用crm接口返回error!");
                        CrmErrorDTO crmErrorDTO = JSON.parseObject(JSON.toJSONString(error), CrmErrorDTO.class);
                        log.info("积分兑换异常返回信息: {}", crmErrorDTO.toString());
                        //添加库存   remove分布式锁
                        productRepository.updateStock(product.getStock(), stock, product.getId());
                        redisUtils.remove(key);
                        if (crmErrorDTO.getCode().compareTo("409180") == 0) {
                            jsonResult.setState(1);
                            jsonResult.setData(crmErrorDTO);
                            jsonResult.setMessage("积分不足，无法兑换");
                            return jsonResult;
                        }
                        jsonResult.setState(1);
                        jsonResult.setData(crmErrorDTO);
                        jsonResult.setMessage("积分兑换异常，请重新尝试");
                        return jsonResult;
                    }
                    PointDTO pointDto = JSON.parseObject(JSON.toJSONString(result), PointDTO.class);
                    //优惠卷需要分配couponId
                    OrderRecord order = new OrderRecord();
                    if (0==product.getType()) {
                        // 实物
                        order.setState(0);
                        order.setOrderType(OrderTypeEnum.ORDER_TYPE_20.getCode());
                    } else {
                        order.setState(1);
                        // 有赞券 微信券
                        order.setOrderType(OrderTypeEnum.ORDER_TYPE_10.getCode());
                        order.setCouponId(product.getCouponId());
                    }
                    BeanUtils.copyProperties(req, order);
                    order.setOrderCode(getOrderCode);

                    order.setType(product.getType());
                    order.setOrderTime(new Date());
                    order.setCreateTime(new Date());
                    order.setUpdateTime(new Date());
                    //添加下发物流状态
                    order.setLogisticsPushState(LogisticsPushStateEnum.LOGISTICS_PUSH_10.getCode());
                    //设置订单总积分 zhaoyl
                    order.setPoints(product.getPoints());
                    //物流地址
                    order.setLogisticsAddress(req.getLogisticsAddress());
                    if(StringUtils.isNotEmpty(req.getSkuId())){
                        order.setSkuId(req.getSkuId());
                    }
                    order = orderRepository.saveAndFlush(order);
                    OrderResp orderResp = new OrderResp();
                    BeanUtils.copyProperties(order, orderResp);
                    OrderCreateResp orderCreateResp = new OrderCreateResp();
                    orderCreateResp.setOrderResp(orderResp);
                    orderCreateResp.setPointDTO(pointDto);
                    List<TaskRecord> list = taskRecordRepository.findByUserIdAndTaskType(req.getUserId(),12);
                    if(list == null || list.size() == 0){
                        TaskRecord taskRecord = new TaskRecord();
                        taskRecord.setCreateTime(new Date());
                        taskRecord.setTaskType(12);
                        taskRecord.setUserId(req.getUserId());
                        taskRecordRepository.save(taskRecord);
                        log.info("本地第一次积分兑礼添加积分完成");
                        String requestUrl1 = Constants.PointIncr.replace("MEMBERSHIP", req.getMembershipId()).replace("ACCESSTOKEN", accessToken);
                        PointDTO dto = new PointDTO();
                        dto.setContentName("第一次兑换赠送积分");
                        dto.setSource("帝亚吉欧会员俱乐部");
                        dto.setDate(timeStamp);
                        dto.setPattern(1);//第一次积分兑礼
                        dto.setPoint(20);
                        OkHttpClient client = new OkHttpClient().newBuilder()
                            .build();
                        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
                        Request request = new Request.Builder()
                            .url(requestUrl1)
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                        try {
                            Response response = client.newCall(request).execute();
                            String jsresult = new String(response.body().bytes());
                            log.info("调用加分接口,返回值:{}", jsresult);
                            response.body().close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    jsonResult.setState(0);
                    jsonResult.setData(orderCreateResp);
                    redisUtils.remove(key);
                };
            } else {
                jsonResult.setState(1);
                jsonResult.setMessage("系统异常，请重试");
            }
        } catch (RestClientException e) {
            redisUtils.remove(key);
            jsonResult.setState(1);
            jsonResult.setMessage("系统异常，请重试");
        } finally {
            redisUtils.remove(key);
        }
        return jsonResult;
    }*/

}
